package cn.moonspace.flowerowner.listener;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.XmlWebApplicationContext;

import cn.moonspace.common.util.ImageUtil;
import cn.moonspace.common.util.Md5Util;
import cn.moonspace.flowerowner.entities.Manager;
import cn.moonspace.flowerowner.entities.Picture;
import cn.moonspace.flowerowner.repositories.ManagerRepository;
import cn.moonspace.flowerowner.repositories.PictureRepository;

/**
 * 数据初始化
 *
 * Created by diyongchao on 14-11-7.
 */
@Component
public class InitDataListener implements ApplicationListener {

    @Autowired
    private ManagerRepository managerRepository;
    @Autowired
    private PictureRepository pictureRepository;

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
    	 if (applicationEvent.getSource() instanceof XmlWebApplicationContext) {
    		 XmlWebApplicationContext context = (XmlWebApplicationContext)applicationEvent.getSource();
    		 if(managerRepository.findByUsername("admin") == null) {
    			 Manager manager = new Manager();
    			 manager.setUsername("admin");
    			 manager.setPassword(Md5Util.MD5("admin"));
    			 managerRepository.save(manager);
    		 }
    		 //添加了大尺寸缩略图，补全旧数据
    		String realPath = context.getServletContext().getRealPath("WEB-INF/uploaded/");
    		File waterFile = new File(context.getServletContext().getRealPath("WEB-INF/images/"), "watermark.png");
    		List<Picture> picList = pictureRepository.findPicturesWithoutThumbPathLarge();
    		for(Picture pic : picList){
    			File imageFile = new File(realPath, pic.getImagePath());
    			String thumbPathLarge = pic.getImagePath().replace(ImageUtil.SUFFIX_JPG, ImageUtil.SUFFIX_JPG_THUMB_LARGE);
    			try {
    				Thumbnails.of(imageFile).size(570, 400).outputQuality(0.9f)
	        				.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(waterFile),0.5f)
    		        		.toFile(realPath + "/" + thumbPathLarge);
    				pic.setThumbPathLarge(thumbPathLarge);
    				pictureRepository.save(pic);
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
		}

    }

}
